﻿using System;
using System.Diagnostics;
using System.IO;
using SFML.Audio;
using SFML.Graphics;
using SFML.Window;

namespace SFMLPlatformerEngine {

	class Program {

		static void Main() {

			RenderWindow window = new RenderWindow(new VideoMode(800, 600), "SFML.Net Game", Styles.Default);

			window.Closed += (sender, e) => { window.Close(); };

			window.KeyPressed += (sender, e) => {
				if(e.Code == Keyboard.Key.Escape)
					window.Close();
			};

			Map map = new Map(new Texture("res/map.png"));
			map.LoadTileMap(File.ReadAllLines("res/map.dat"));

			Player player = new Player(new Texture("res/fang.png"), map);

			RectangleShape back = new RectangleShape(new Vector2f(4000, 4000)) {
				Texture = new Texture("res/back.png"),
				TextureRect = new IntRect(0, 0, 1024, 683)
			};

			Music musik = new Music("res/contra.ogg") { Loop = true, Volume = 20 };
			musik.Play();

			Stopwatch sw = new Stopwatch();

			while(window.IsOpen()) {

				if(Keyboard.IsKeyPressed(Keyboard.Key.Left)) {
					player.dx = -0.2f;
					player.direction = Direction.Left;
				}

				if(Keyboard.IsKeyPressed(Keyboard.Key.Right)) {
					player.dx = 0.2f;
					player.direction = Direction.Right;
				}

				if(Keyboard.IsKeyPressed(Keyboard.Key.Up)) {
					if(player.onGround) {
						player.dy = -0.4f;
						player.onGround = false;
					}

				}

				float time = sw.ElapsedMilliseconds * 4;
				sw.Restart();

				player.Update(time);

				if(player.rect.Left > window.Size.X / 2)
					map.offsetX = (int)(player.rect.Left - window.Size.X / 2);
				map.offsetY = (int)(player.rect.Top - window.Size.Y / 2);

				window.Clear(Color.White);

				back.Position = new Vector2f(-((back.Size.X - window.Size.X) / 2) - map.offsetX / 4, -((back.Size.Y - window.Size.Y) / 2) - map.offsetY / 4);
				back.Scale = new Vector2f(2, 2);
				window.Draw(back);

				map.objects.Update(time);

				for(int i = 0; i < map.height; i++)
					for(int j = 0; j < map.width; j++) {
						if(map.tileMap[i][j] == ' ')
							continue;

						GameObject o = map.objects[map.tileMap[i][j]];
						o.sprite.Position = new Vector2f(j * 32 - map.offsetX, i * 32 - map.offsetY);
						window.Draw(o.sprite);
					}

				window.Draw(player.sprite);
				window.Display();
				window.DispatchEvents();
			}
		}
	}
}
